package com.luo.ai.assistant.chat.memory;

import com.luo.ai.assistant.chat.ChatConsts;
import com.luo.ai.assistant.conv.dao.ChatMapper;
import com.luo.ai.assistant.conv.model.Chat;
import com.luo.ai.assistant.conv.model.ChatQuery;
import com.luo.ai.assistant.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * DAO聊天记录实现
 *
 * @author luohq
 * @date 2025-02-02 10:28
 */
@Component
public class MyDaoChatMemory implements ChatMemory {

    private static final Logger log = LoggerFactory.getLogger(MyDaoChatMemory.class);

    private final ChatMapper chatMapper;
    /**
     * 默认获取最近20条聊天记录
     */
    private int lastN = ChatConsts.DEFAULT_CHAT_MEMORY_SIZE;

    public MyDaoChatMemory(ChatMapper chatMapper) {
        this.chatMapper = chatMapper;
    }

    public void setLastN(int lastN) {
        this.lastN = lastN;
    }

    @Override
    public void add(String conversationId, List<Message> messages) {
        // 将消息转换为聊天记录
        List<Chat> chatList = messages.stream()
                .map(message -> ChatMessageConvertor.toChat(conversationId, message))
                .collect(Collectors.toList());
        // 插入聊天记录
        log.debug("[ChatMemory] DAO - add chats - chat count: {}, chat list: {}", chatList.size(), JsonUtils.toJson(chatList));
        this.chatMapper.insert(chatList);
    }

    @Override
    public List<Message> get(String conversationId) {
        if (0 >= lastN) {
            log.debug("[ChatMemory] DAO - get chat history: lastN is {} and Return Empty Chat List!", lastN);
            return List.of();
        }
        // 调用DAO查询聊天记录
        ChatQuery chatQuery = new ChatQuery();
        chatQuery.setConvId(Long.valueOf(conversationId));
        chatQuery.setLimit(Long.valueOf(lastN));
        List<Chat> chatHistory = this.chatMapper.findChatHistory(chatQuery);
        log.debug("[ChatMemory] DAO - get chat history - chat count: {}, chat list: {}", chatHistory.size(), JsonUtils.toJson(chatHistory));
        if (CollectionUtils.isEmpty(chatHistory)) {
            return List.of();
        }
        // 将聊天记录转换为消息
        return chatHistory.stream()
                .map(ChatMessageConvertor::toMessage)
                .collect(Collectors.toList());
    }

    @Override
    public void clear(String conversationId) {
        //TODO 注意调用时机
        log.debug("[ChatMemory] DAO - clear chat of conversation: {}", conversationId);
        this.chatMapper.deleteByConvIds(List.of(Long.valueOf(conversationId)));
    }
}
